package cn.bone.zk.zk01;

import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ZkClient {

    private ZooKeeper zkClient;

    public void init(){

        // 3个参数（1、zk地址，2、超时时间，毫秒数，3、监听器）
        String connectString = "192.168.1.5:2001,192.168.1.5:2002,192.168.1.5:2003";
        int sessionTimeout = 2000;
        try {
            zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
                @Override
                public void process(WatchedEvent event) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void create(){
        String path = "/wuhan";
        byte[] data = new byte[0];
        try {
            data = "今天天气不错哦".getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            String s = zkClient.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println(s);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void getChildren(){
        try {
            List<String> children = zkClient.getChildren("/", true);
            System.out.println(JSON.toJSONString(children));
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void exist(){
        try {
            Stat exist = zkClient.exists("/wuhan", false);
            System.out.println(exist==null? "empty" : exist.toString());
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
